import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";
import postCssPxToRem from "postcss-pxtorem";
import * as const_var from "./src/config/const_var.ts";
// @ts-ignore
import { svgBuilder } from "./src/plugins/svgBuilder.js";
// @ts-ignore
import updateVersion from "./src/plugins/updateVersion.js";

import svgLoader from "vite-svg-loader";
import { ViteImageOptimizer } from "vite-plugin-image-optimizer";

export default defineConfig(({ mode }) => {
  const envDir = "./env";
  const config = loadEnv(mode, resolve(process.cwd(), envDir));
  return {
    base: "/",
    envDir: envDir,
    envPrefix: ["VITE_"],
    plugins: [
      vue(),
      vueJsx(),
      AutoImport({
        imports: ["vue", "vue-router"],
        resolvers: [VantResolver()],
        dts: "src/types/auto-import.d.ts",
        dirs: ["src/assets/js/*", "src/utils/*.*", "./src/api/*"],
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/],
      }),
      Components({
        resolvers: [VantResolver()],
        dts: "src/types/components.d.ts",
        dirs: ["src/components"],
      }),
      svgLoader(),
      svgBuilder("./src/assets/svg/"),
      updateVersion(config.VITE_NAME),
      ViteImageOptimizer({
        png: {
          quality: 100,
        },
        jpg: {
          quality: 100,
        },
        jpeg: {
          quality: 100,
        },
        webp: {
          quality: 100,
        },
      }),
    ],
    build: {
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: false,
      minify: "terser",
      chunkSizeWarningLimit: 1024 * 10,
      assetsInlineLimit: 1024 * 4,
      terserOptions: {
        output: {
          comments: true,
        },
        compress: {
          drop_console: false,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        input: {
          // 单页面应用
          index: resolve(__dirname, "index.html"),
        },
        output: {
          // 静态资源分类打包
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks: (id) => {
            if (id.includes("node_modules")) {
              if (id.includes("vue")) return "vueJS";
              if (id.includes("axios")) return "axiosJS";
            }
          },
        },
      },
    },
    server: {
      port: 65529,
      host: "0.0.0.0",
      proxy: {
        [config.VITE_API_URL]: {
          target: config.VITE_TARGET,
          changeOrigin: true,
          rewrite: (path: string) => path.replace(/^\/api/, ""),
        },
      },
    },
    resolve: {
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
      alias: {
        "@": resolve(__dirname, "src"),
        "@views": resolve(__dirname, "src/views"),
        "@assets": resolve(__dirname, "src/assets"),
        "@components": resolve(__dirname, "src/components"),
        "@layout": resolve(__dirname, "src/components/layout"),
        "@img": resolve(__dirname, "src/assets/img"),
        "@store": resolve(__dirname, "src/store"),
        "@styles": resolve(__dirname, "src/styles"),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          charset: false,
          additionalData: `@use '@/styles/variables.scss' as *;
          $scss-env: ${config.VITE_NAME};
          $scss-classNameHomeWrapListItem: ${const_var.classNameHomeWrapListItem};
          $scss-classNameHomeScrollSnap: ${const_var.classNameHomeScrollSnap};
          $scss-classNameHomeListItem: ${const_var.classNameHomeListItem};
          $scss-classNameHomeItemList: ${const_var.classNameHomeItemList};
          $scss-classNameNextStory: ${const_var.classNameNextStory};
          $scss-classNameProgressBar: ${const_var.classNameProgressBar};
          $scss-classNameArticleDetailItem: ${const_var.classNameArticleDetailItem};
          $scss-classNameActiveScrollParent: ${const_var.classNameActiveScrollParent};`,
          api: "modern-compiler", // or 'modern'
        },
      },
      modules: {},
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: const_var.rootValue, // 1rem 的大小
            propList: ["*"], // 需要转换的属性，*(全部转换)
            unitPrecision: const_var.unitPrecision, // 转换精度，保留的小数位数
            selectorBlackList: ["van"],
            exclude: (filePath: string) => {
              if (/src\/assets\/css\/style.css/.test(filePath)) {
                return true;
              }
              return false;
            },
          }),
        ],
      },
    },
  };
});
